package com.wechat.service.account.starter.accountManage;

import com.alibaba.fastjson.JSONObject;
import com.wechat.service.account.dto.accountManage.ParamsQRCodeCreateReqDTO;
import com.wechat.service.account.dto.accountManage.ParamsQRCodeCreateRespDTO;
import com.wechat.service.account.starter.AccessTokenService;
import com.wechat.service.account.starter.BaseWechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author yanggld
 * @Date 2019/7/10-16:14
 * @Description
 * 生成带参数的二维码
 */
@Slf4j
@Service
public class ParamsQRCodeService extends BaseWechatService {

	/**
	 * 请求创建临时二维码
	 * 临时二维码，是有过期时间的，最长可以设置为在二维码生成后的30天（即2592000秒）后过期，但能够生成较多数量。
	 * 临时二维码主要用于帐号绑定等不要求二维码永久保存的业务场景
	 * @param dto  带参二维码创建的dto
	 * @return
	 */
	public ParamsQRCodeCreateRespDTO reqCreateTempQRCode(ParamsQRCodeCreateReqDTO dto){
		JSONObject params = new JSONObject();
		params.put("expire_seconds",dto.getExpire_seconds());
		params.put("action_name",dto.getAction_name());

		Map<String,Object> sceneValueParam = new HashMap<>();
		if (dto.getScene_id() != null) {
			sceneValueParam.put("scene_id",dto.getScene_id());
		}
		if (dto.getScene_str() != null) {
			sceneValueParam.put("scene_str",dto.getScene_str());
		}

		Map<String,Object> sceneParam = new HashMap<>();
		sceneParam.put("scene",sceneValueParam);

		params.put("action_info",sceneParam);
		log.info("*******创建临时二维码参数：{}*******",JSONObject.toJSONString(dto));
		ResponseEntity<ParamsQRCodeCreateRespDTO> responseEntity = restTemplate.postForEntity(buildQRCodeUrl(), params, ParamsQRCodeCreateRespDTO.class);
		ParamsQRCodeCreateRespDTO respDTO = responseEntity.getBody();
		log.info("*******创建临时二维码结果：{}*******",JSONObject.toJSONString(respDTO));
		return respDTO;
	}

	/**
	 * 请求创建永久二维码
	 * 永久二维码，是无过期时间的，但数量较少（目前为最多10万个）。
	 *  永久二维码主要用于适用于帐号绑定、用户来源统计等场景。
	 * @param dto  带参二维码创建的dto
	 * @return
	 */
	public ParamsQRCodeCreateRespDTO reqCreatePermQRCode(ParamsQRCodeCreateReqDTO dto){
		JSONObject params = new JSONObject();
		params.put("action_name",dto.getAction_name());

		Map<String,Object> sceneValueParam = new HashMap<>();
		if (dto.getScene_id() != null) {
			sceneValueParam.put("scene_id",dto.getScene_id());
		}
		if (dto.getScene_str() != null) {
			sceneValueParam.put("scene_str",dto.getScene_str());
		}

		Map<String,Object> sceneParam = new HashMap<>();
		sceneParam.put("scene",sceneValueParam);

		params.put("action_info",sceneParam);
		log.info("*******创建永久二维码参数：{}*******",JSONObject.toJSONString(params));
		ResponseEntity<ParamsQRCodeCreateRespDTO> responseEntity = restTemplate.postForEntity(buildQRCodeUrl(), params, ParamsQRCodeCreateRespDTO.class);
		ParamsQRCodeCreateRespDTO respDTO = responseEntity.getBody();
		log.info("*******创建永久二维码结果：{}*******",JSONObject.toJSONString(respDTO));
		return respDTO;
	}


	/**
	 * 获取qrcode地址
	 * @param ticket
	 * @return
	 */
	public String getQRCodeUrl(String ticket){
		String ticketDecoded = null;
		try {
			ticketDecoded = URLDecoder.decode(ticket, "utf-8");
		} catch (UnsupportedEncodingException e) {
			log.error("ticket：{}，编码错误：{}",ticket,e.getMessage());
		}
		return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticketDecoded;
	}

	/**
	 * 保存qrcode
	 * @param ticket
	 * @param path 保存地址
	 */
	public void saveQRcode(String ticket,String path){
		String ticketDecoded = null;
		try {
			ticketDecoded = URLDecoder.decode(ticket, "utf-8");
		} catch (UnsupportedEncodingException e) {
			log.error("ticket：{}，编码错误：{}",ticket,e.getMessage());
		}
		String qrUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticketDecoded;

		// 保存ticket到本地
		try {
			//请求的路径
			URL url  = new URL(qrUrl );
			DataInputStream dataInputStream = new DataInputStream(url.openStream());
			//下载的位置及文件名
			FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			int length;

			while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			fileOutputStream.write(output.toByteArray());
			dataInputStream.close();
			fileOutputStream.close();
		} catch (Exception e) {
			log.info("保存二维码失败:{}",e.getMessage());
		}
	}


	public String buildQRCodeUrl(){
		return "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessTokenService.getAccessToken();
	}
}
